<template>
  <div class="equity-mall-container bg-white">
    <el-scrollbar style="height: calc(100vh - 100px)">
      <div class="center-board-item">
        <h4>基础信息</h4>
        <el-form
          :model="productFormData"
          label-width="100px"
          :rules="productFormRules"
          ref="formRef"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productFormData.name" class="input-width" />
          </el-form-item>
          <el-form-item label="商品封面" prop="coverImage">
            <MultiImageUpload v-model="productFormData.coverImage" />
          </el-form-item>
          <el-form-item label="商品轮播图" prop="banners">
            <MultiImageUpload v-model="productFormData.banners" />
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-cascader
              class="input-width"
              v-model="productFormData.categoryId"
              :options="categoryList"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children',
                emitPath: false,
                checkStrictly: true,
              }"
              clearable
              :show-all-levels="false"
            />
          </el-form-item>
          <!-- 商品描述 -->
          <el-form-item label="商品描述" prop="fdescribe">
            <el-input
              v-model="productFormData.fdescribe"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
            />
          </el-form-item>
          <el-form-item label="商品详情" prop="details">
            <div>
              <WangEditor v-model="productFormData.details" />
            </div>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="productFormData.sort" :min="1" :max="1000" />
          </el-form-item>
          <div class="flex justify-between items-center mt-10 border-t-2 border-gray-200">
            <h4>规格信息</h4>
            <div>
              <el-button type="primary" plain class="ml-5" @click="openManageSpecType">
                规格管理
              </el-button>
              <!-- <el-button type="primary" plain class="ml-5" @click="openManageSpec">
                管理属性规格
              </el-button> -->
            </div>
          </div>
          <el-form-item label="选择属性" prop="prices">
            <el-select
              class="input-width"
              v-model="productFormData.prices"
              multiple
              filterable
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择属性"
              @change="handleSpecTypeBlur"
            >
              <el-option
                v-for="item in specTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="!productFormData.prices?.length">
            <el-form-item label="商品价格" prop="price">
              <el-input
                v-model="productFormData.price"
                type="number"
                :formatter="formatter"
                :parser="formatter"
                placeholder="请输入商品价格"
              />
            </el-form-item>
            <el-form-item label="积分价格" prop="pointsPrice">
              <el-input
                v-model="productFormData.pointsPrice"
                type="number"
                placeholder="请输入积分价格"
                :formatter="formatter"
                :parser="formatter"
              />
            </el-form-item>
          </template>
          <div class="m-5">
            <el-table :data="tableData" style="width: 100%" v-if="productFormData.prices?.length">
              <el-table-column
                v-for="item in tableColumnsData"
                :key="item.id"
                :prop="item.prop"
                :label="item.label"
              >
                <template #default="scope">
                  <el-form-item
                    label-width="auto"
                    :prop="`${scope.row}.${scope.$index}.${item.prop}`"
                  >
                    <el-select
                      v-model="scope.row[item.prop]"
                      :placeholder="item.spec.length > 0 ? '请选择' : '无规格'"
                      size="large"
                    >
                      <el-option v-for="one in item.spec" :key="one" :label="one" :value="one" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="价格（元）">
                <template #default="scope">
                  <el-form-item :prop="`${scope.row}.${scope.$index}.price`" label-width="auto">
                    <el-input
                      v-model="scope.row.price"
                      @blur="() => (scope.row.pointsPrice = scope.row.price * 10)"
                      :formatter="formatter"
                      type="number"
                      :parser="formatter"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="积分价格(价格*10)">
                <template #default="scope">
                  <el-form-item
                    :prop="`${scope.row}.${scope.$index}.pointsPrice`"
                    label-width="auto"
                  >
                    <el-input
                      v-model="scope.row.pointsPrice"
                      :formatter="formatter"
                      :parser="formatter"
                      type="number"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="操作" align="center">
                <template #default="scope">
                  <el-button type="primary" link class="ml-5" @click="tableData.push({})">
                    新增一条
                  </el-button>
                  <el-button type="danger" link class="ml-5" @click="deleteOne(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form-item label="是否上架" prop="isShelf">
            <el-radio-group v-model="productFormData.isShelf" direction="vertical">
              <el-radio label="是" :value="1" />
              <el-radio label="否" :value="0" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上架类型" prop="shelfType" v-if="productFormData.isShelf === 1">
            <el-radio-group v-model="productFormData.shelfType" direction="vertical">
              <el-radio label="立即上架" :value="1" />
              <!-- <el-radio label="定时上架" :value="2" /> -->
            </el-radio-group>
            <el-form-item label="" prop="shelfTime" v-if="productFormData.shelfType === 2">
              <el-date-picker
                v-model="productFormData.shelfTime"
                type="datetime"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD hh:mm:ss"
                class="ml-5"
              />
            </el-form-item>
          </el-form-item>
        </el-form>
        <div class="flex justify-end">
          <el-button type="primary" size="large" @click="submitForm">保存</el-button>
          <!-- <el-button size="large" @click="submitForm">返回</el-button> -->
        </div>
      </div>
      <input id="copyNode" type="hidden" />
    </el-scrollbar>
    <ManageSpecType
      ref="manageSpecTypeRef"
      @updateSpecTag="getAllProductProperty"
      :specTypeOptions="specTypeOptions"
    />
  </div>
</template>

<script setup>
import ManageSpecType from "./ManageSpecType.vue";
import EquityMallAPI from "@/api/equitymall";
import router from "@/router";
const route = useRoute();
const props = defineProps({
  type: {
    type: Number,
    default: 1,
  },
  defaultData: {
    type: Object,
    default: null,
  },
  hasCategory: {
    default: true,
  },
});
/**
 * 表单数据
 *
 */
const productFormRules = ref({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  coverImage: [{ required: true, message: "请上传商品封面", trigger: "blur" }],
  banners: [{ required: true, message: "请上传商品轮播图", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
  fdescribe: [{ required: true, message: "请输入商品描述", trigger: "blur" }],
  details: [{ required: true, message: "请输入商品详情", trigger: "change" }],
  shelfType: [{ required: true, message: "请选择上架类型", trigger: "blur" }],
  prices: [
    {
      required: true,
      message: "请填写完整下列表格",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback();
          return;
        }
        let keyNumber = tableColumnsData.value.length + 2; // 规格id们 + 价格 + 积分价格
        let flag = false;
        tableData.value.forEach((item) => {
          if (Object.keys(item).length !== keyNumber) {
            flag = true;
          }
        });
        if (flag) {
          callback(new Error("请填写完整下列表格"));
        } else {
          callback();
        }
      },
    },
  ],
  price: [
    { type: "number", message: "金额必须为数字" },
    { type: "number", max: 10000000, message: "金额超出最大值" },
    { required: true, message: "请输入商品价格", trigger: "blur" },
  ],
  pointsPrice: [
    { type: "number", message: "积分必须为数字" },
    { type: "number", max: 10000000, message: "积分超出最大值" },
    { required: true, message: "请输入积分价格", trigger: "blur" },
  ],
  tablePrice: [
    { type: "number", message: "金额必须为数字" },
    { type: "number", max: 10000000, message: "金额超出最大值" },
    { required: true, message: "请输入商品价格", trigger: "blur" },
  ],
  tablePointsPrice: [
    { type: "number", message: "积分必须为数字" },
    { type: "number", max: 10000000, message: "积分超出最大值" },
    { required: true, message: "请输入积分价格", trigger: "blur" },
  ],
});
const productFormData = ref({
  name: "",
  sort: 1,
  coverImage: [],
  banners: [],
  fdescribe: "",
  details: "",
  prices: [], // 规格id
  specType: 2, // 规格类型，1多规格;2单规格
  isShelf: 1, // 是否上架 1上架 0下架
  shelfType: 1, // 上架类型 1立即上架 2定时上架
  shelfTime: "", // 定时上架时间
});
const manageSpecTypeRef = ref(null);
const openManageSpecType = () => {
  manageSpecTypeRef.value.openDialog();
};

// 所有属性
const specTypeOptions = ref([]);
const specTypeOptionsObj = computed(() => {
  let obj = {};
  specTypeOptions.value.forEach((item) => {
    obj[item.id] = item;
  });
  return obj;
});

/***
 * 选择完属性后，
 * 1. 需要动态处理规格标签
 * 2. 需要动态处理 表格数据
 */
const specTypeActiveOptions = ref([]);
const handleSpecTypeBlur = async (value) => {
  productFormData.prices = value;

  specTypeActiveOptions.value = specTypeOptions.value.filter((item) => {
    return productFormData.value.prices.includes(item.id);
  });
  handleTableData();
};
const tableData = ref([]);
const tableColumnsData = ref([]);
const handleTableData = () => {
  tableColumnsData.value = specTypeActiveOptions.value.map((item) => {
    let tags = item?.tags?.split(",") || [];
    return {
      label: item.name,
      prop: item.id, // 属性的名字 specTag
      id: item.id,
      customSlot: item.id,
      spec: tags,
    };
  });
  tableData.value = [{}];
};
// 删除表格数据
const deleteOne = (row) => {
  tableData.value = tableData.value.filter((item) => item !== row);
};
// 查询所有属性
const getAllProductProperty = async () => {
  try {
    const res = await EquityMallAPI.getAllProductProperty();
    specTypeOptions.value = res;
  } catch (error) {
    console.error(error);
  }
};
const categoryList = ref([]);
const categoryPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 分页查询产品分类
const getProductCategoryPage = async () => {
  try {
    const res = await EquityMallAPI.getProductCategoryPage(categoryPageQuery);
    categoryList.value = buildTree(res.list);
  } catch (error) {
    console.error(error);
  }
};
// 处理数据
function buildTree(nodes) {
  // 创建一个映射表，用于快速查找父节点
  const nodeMap = {};
  nodes.forEach((node) => {
    nodeMap[node.id] = { ...node, children: [] }; // 添加 children 属性
  });

  // 构建树形结构
  const tree = [];
  nodes.forEach((node) => {
    if (node.parentId === null) {
      // 如果 parentId 为 null，则为根节点
      tree.push(nodeMap[node.id]);
    } else {
      // 如果有 parentId，则找到对应的父节点并添加到 children 中
      const parent = nodeMap[node.parentId];
      if (parent) {
        parent.children.push(nodeMap[node.id]);
      }
    }
  });
  return tree;
}
const formRef = ref(null);
const submitForm = async () => {
  console.log(tableData.value, "tableData");
  formRef.value.validate(async (valid) => {
    if (valid) {
      let params = {
        ...productFormData.value,
        coverImage: JSON.stringify(productFormData.value.coverImage),
        banners: productFormData.value.banners.map((item, index) => {
          return {
            imageUrl: item.url,
            sort: index + 1,
          };
        }),
        //上架类型:1立即上架2;定时上架
        shelfType: productFormData.value.shelfType === 1 ? 1 : 2,
      };
      if (tableData.value.length > 0) {
        params.prices = tableData.value.map((item) => {
          // 除了这两个字段，其他字段都是规格id，需要处理
          let directName = ["price", "pointsPrice"];
          let one = {
            ext: [],
            price: item.price,
            pointsPrice: item.pointsPrice,
          };
          Object.keys(item).forEach((key) => {
            if (!directName.includes(key)) {
              one.ext.push({
                propertyId: key,
                tags: item[key],
              });
            }
          });
          //one.productSpecIds = one.productSpecIds.join(",");
          return one;
        });
      } else {
        params.prices = [
          {
            ext: [],
            price: productFormData.value.price,
            pointsPrice: productFormData.value.pointsPrice,
          },
        ];
      }
      try {
        let id = route.query?.id;
        if (id) {
          params.id = id;
          await EquityMallAPI.editProduct(params);
          ElMessage.success("编辑成功");
        } else {
          await EquityMallAPI.addProduct(params);
          ElMessage.success("添加成功");
        }
        router.push({
          path: "/equitymall/mall",
        });
      } catch (error) {
        console.error(error);
      }
    }
  });
};
let productDetail = ref({});
const getProductDetailById = async () => {
  try {
    const res = await EquityMallAPI.getProductDetailById(id);
    productDetail.value = res;
  } catch (error) {
    console.error(error);
  }
};
const handleDefaultData = () => {
  productFormData.value = { ...productDetail.value };
  productFormData.value.coverImage = JSON.parse(productDetail.value.coverImage);
  productFormData.value.banners = productDetail.value.banners.map((item) => {
    return {
      url: item.imageUrl,
      name: item.imageUrl,
    };
  });
  productFormData.value.prices = productDetail.value.prices[0].ext.map((item) => {
    return item.propertyId;
  });
  handleSpecTypeBlur();
  tableData.value = productDetail.value.prices.map((item) => {
    let one = {
      price: item.price,
      pointsPrice: item.pointsPrice,
    };
    item.ext.forEach((item) => {
      one[item.propertyId] = item.tags;
    });
    return one;
  });
};
const formatter = (value) => {
  return value > 10000000000 ? 10000000000 : value;
};
watchEffect(
  () => {
    console.log(tableData.value, "tableData");
  },
  {
    deep: true,
  }
);
onMounted(async () => {
  await getAllProductProperty();
  productDetail.value = {};
  const id = route.query.id; // 获取动态路由参数
  if (id) {
    await getProductDetailById();
    handleDefaultData();
  }
  getProductCategoryPage();
});

const id = route.query.id;
</script>

<style lang="scss">
.equity-mall-container {
  margin: 20px;
  padding: 10px 30px;
  height: calc(100vh - 100px);
  .center-board-item {
    padding-bottom: 50px;
    .input-width {
      width: 300px;
    }
  }
}
</style>
